import pandas as pd
import numpy as np

from paper.trace.tools_coord_trans import rthetaphi_to_xyz, xyz_to_latilongalti


################################################ 主函数 #############################################
def format_python_aeconvlstm(path_csv_dataset, path_csv_before, path_csv_after):
    # 1.读取 AE-Conv2DLSTM 结果的 .csv 文件
    df = pd.read_csv(path_csv_before)
    aeconvlstm_theta = df['trace_th_smooth']
    aeconvlstm_phi = df['trace_ph_smooth']
    aeconvlstm_theta = np.array(aeconvlstm_theta)
    aeconvlstm_phi = np.array(aeconvlstm_phi)
    # 2.读取 dataset 的 经纬度 和 r
    df_dataset = pd.read_csv(path_csv_dataset)
    latitudes_ori, longitudes_ori, altitudes_ori = \
        df_dataset['lati_smooth'].values, df_dataset['long_smooth'].values, df_dataset['alti_smooth'].values
    r_ori = df_dataset['r_smooth'].values
    lati_0, long_0, alti_0 = latitudes_ori[0], longitudes_ori[0], altitudes_ori[0]
    # 3.从(theta,phi)转换回(x,y)和经纬度
    aeconvlstm_x, aeconvlstm_y, aeconvlstm_z = rthetaphi_to_xyz(r_ori, aeconvlstm_theta, aeconvlstm_phi)
    # 直角坐标系(x,y)转换回经纬度
    aeconvlstm_lati, aeconvlstm_long, aeconvlstm_alti = xyz_to_latilongalti(lati_0, long_0, alti_0,
                                                                            aeconvlstm_x, aeconvlstm_y, aeconvlstm_z)
    # 4. 创建含恢复结果的 DataFrame 并保存
    recovery_df = pd.DataFrame({
        'latitudes_ori': latitudes_ori,
        'longitudes_ori': longitudes_ori,
        'altitudes_ori': altitudes_ori,
        'aeconvlstm_lati': aeconvlstm_lati,
        'aeconvlstm_long': aeconvlstm_long,
        'aeconvlstm_alti': aeconvlstm_alti,
        'aeconvlstm_x': aeconvlstm_x,
        'aeconvlstm_y': aeconvlstm_y,
        'aeconvlstm_z': aeconvlstm_z,
        'aeconvlstm_theta': aeconvlstm_theta,
        'aeconvlstm_phi': aeconvlstm_phi
    })

    recovery_df.to_csv(path_csv_after, index=False)
    print(f"恢复结果已保存到 {path_csv_after}")




if __name__=="__main__":
    format_python_aeconvlstm('uav_dataset_interpl_test_2025-10-21.csv',
                             'y_out_psll_point.csv',
                             "aeconvlstm_out_UAV_Measure_1_test_coord_2025-10-21.csv")